<template>
  <div class="app-container">
    <el-table v-loading="loading" :data="equipmentarr" border style="margin-bottom: 30px"
      v-if="this.$route.query.type === 'equipment'">
      <el-table-column label="设备名称" align="center" prop="nickName" />
      <el-table-column label="蓝牙mac地址" align="center" prop="deviceId" />
      <el-table-column label="型号" align="center" prop="equipmentModel" />
      <el-table-column label="使用人" align="center" prop="yhMinUser.uname" />
      <el-table-column label="电话" align="center" prop="yhMinUser.uphone" />
      <el-table-column label="绑定时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleClickDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-table v-loading="loading" :data="userarr" border style="margin-bottom: 30px"
      v-if="this.$route.query.type === 'user'">
      <el-table-column label="姓名" align="center" prop="uname" />
      <el-table-column label="电话" align="center" prop="uphone" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="身高(cm)" align="center" prop="height" />
      <el-table-column label="体重(kg)" align="center" prop="weight" />
      <el-table-column label="药物类型" align="center" prop="drugCategoryName" />
      <el-table-column label="最近服用药" align="center" prop="recentMedication" />
      <el-table-column label="服用频率" align="center" prop="drugFrequencyName" />
      <el-table-column label="绑定设备" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleClickDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px" v-if="this.$route.query.type === 'user'">
      设备名称
      <el-select v-model="seleceVal" placeholder="请选择" @change="handleChangeEquipment">
        <el-option v-for="item in equipmentList" :key="item.value" :label="item.nickName" :value="item.deviceId">
        </el-option>
      </el-select>
    </div>
    <el-row :gutter="10" class="mb8">
      <div class="tabButton">
        <el-button style="width: 120px" type="warning" size="mini" v-for="(item,index) in tabButtonList" :key="index"
          :plain="item.selectBtn" @click="handleUntreated(item)">{{ item.tabButtonValue }}</el-button>
      </div>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" :disabled="single" @click="handleBtn">批量处理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system/health:prewarn:export']">导出exl</el-button>
      </el-col>
      <el-col :span="1.5">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-col>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预警类别" prop="prewarnHealthType">
        <el-select v-model="queryParams.prewarnHealthType" placeholder="请选择预警类别" clearable>
          <el-option v-for="dict in dict.type.prewarn_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select v-model="queryParams.prewarnQuery" placeholder="请选择" clearable @change="selectTrigger">
          <el-option label="姓名" value="userName"></el-option>
          <el-option label="电话" value="userPhone"></el-option>
          <el-option label="紧急联系人" value="relativesName"></el-option>
          <el-option label="紧急电话" value="relativesPhone"></el-option>
          <el-option label="设备名称" value="name"></el-option>
          <el-option label="已读" value="prewarnHealthStatus1"></el-option>
          <el-option label="未读" value="prewarnHealthStatus2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="prewarnTempValue">
        <el-input v-model="queryParams.prewarnTempValue" placeholder="请输入" clearable @clear="clearFn"
          @blur="prewarnHandleBlur" />
      </el-form-item>
      <el-form-item label="" prop="prewarnHealthTime">
        <el-date-picker v-model="time" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" @change="changetime" :clearable="false" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="prewarnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" :selectable="selectable" width="55" align="center" />
      <el-table-column label="序号" prop="prewarnId" width="55" align="center" />
      <el-table-column label="预警类别" align="center" prop="prewarnHealthType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.prewarn_type" :value="scope.row.prewarnHealthType" />
        </template>
      </el-table-column>
      <el-table-column label="预警值" align="center" prop="prewarnHealthValue" />
      <el-table-column label="预警时间" align="center" prop="prewarnHealthTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.prewarnHealthTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预警描述" align="center" prop="prewarnHealthContent" show-overflow-tooltip />
      <el-table-column label="预警状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.prewarnHealthStatus == 'read'" type="success">已读</el-tag>
          <el-tag v-if="scope.row.prewarnHealthStatus == 'unread'" type="danger">未读</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="蓝牙mac地址" align="center" prop="prewarnHealthDeviceId" show-overflow-tooltip />
      <el-table-column label="设备名称" align="center" prop="nickName" />
      <el-table-column label="型号" align="center" prop="equipmentModel" />
      <el-table-column label="使用人" align="center" prop="userName" />
      <el-table-column label="电话" align="center" prop="userPhone" />
      <el-table-column label="紧急联系人" align="center" prop="relativesName" />
      <el-table-column label="紧急电话" align="center" prop="relativesPhone" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-if="scope.row.prewarnHealthHandleStatus === '0'"
            @click="handleBtn(scope.row)">处理</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">用户详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改预警类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预警类别" prop="prewarnHealthType">
          <el-select v-model="form.prewarnHealthType" placeholder="请选择预警类别">
            <el-option v-for="dict in dict.type.prewarn_type" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警值" prop="prewarnHealthValue">
          <el-input v-model="form.prewarnHealthValue" placeholder="请输入预警值" />
        </el-form-item>
        <el-form-item label="预警时间" prop="prewarnHealthTime">
          <el-date-picker clearable v-model="form.prewarnHealthTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择预警时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预警描述">
          <editor v-model="form.prewarnHealthContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="预警状态">
          <el-radio-group v-model="form.prewarnHealthStatus">
            <el-radio v-for="dict in dict.type.prewarn_status" :key="dict.value" :label="dict.value">{{dict.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备ID" prop="prewarnHealthDeviceId">
          <el-input v-model="form.prewarnHealthDeviceId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="联系人ID" prop="prewarnHealthDeviceUserid">
          <el-input v-model="form.prewarnHealthDeviceUserid" placeholder="请输入联系人ID" />
        </el-form-item>
        <el-form-item label="紧急联系人ID" prop="prewarnHealthDeviceContactid">
          <el-input v-model="form.prewarnHealthDeviceContactid" placeholder="请输入紧急联系人ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listPrewarn,
    getPrewarn,
    delPrewarn,
    addPrewarn,
    updatePrewarn,
    updateHandlePrewarn
  } from "@/api/system/health/prewarn";
  import {
    getMiniuser
  } from "@/api/system/miniuser";
  import {
    listEquipment,
  } from "@/api/system/equipment";
  import {
    getListByPhone
  } from "@/api/motion";

  export default {
    name: "Prewarn",
    dicts: ['prewarn_status', 'prewarn_type'],
    data() {
      return {
        time: [],
        tabButtonList: [{
            tabButtonValue: '未处理',
            selectBtn: false
          },
          {
            tabButtonValue: '已处理',
            selectBtn: true
          },
        ],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 预警类别表格数据
        prewarnList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          prewarnHealthType: null, // 预警类别
          prewarnHealthValue: null,
          prewarnHealthTime: null,
          prewarnHealthContent: null,
          prewarnHealthStatus: null,
          prewarnHealthDeviceId: null,
          prewarnHealthDeviceUserid: null,
          prewarnHealthDeviceContactid: null,
          prewarnHealthHandleStatus: '0', // 未处理0、已处理1
          prewarnQuery: null, // 类别
          startDate: null,
          endDate: null,
          prewarnTempValue: null, // 临时存储输入的值
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        userarr: [],
        equipmentarr: [],
        equipmentList: [],
        seleceVal: ''
      };
    },
    created() {
      this.getList();
      this.getUserInfo()
      this.getequipment()
    },
    methods: {
      handleChangeEquipment(val) {
        this.equipmentInfo.deviceId = val
        this.queryParams.deviceId = val
        this.getList()
      },
      handleClickDetail(row) {
        // console.log(row)
        if (this.$route.query.type === "user") {
          this.$router.push({
            path: "/userdet",
            query: {
              id: row.id,
              uphone: row.uphone,
            },
          });
        } else if (this.$route.query.type === "equipment") {
          this.$router.push({
            path: "/userdet",
            query: {
              id: row.yhMinUser.id,
              uphone: row.yhMinUser.uphone,
            },
          });
        } else {
          this.$router.push({
            path: "/equipmentDetails",
            query: {
              id: row.id,
              delFlag: row.delFlag,
            },
          });
        }
      },
      getequipment() {
        this.loading = true;
        listEquipment({
          id: this.$route.query.id,
        }).then((response) => {
          this.equipmentarr = response.rows;
          this.loading = false;
        });
      },
      getUserInfo() {
        getMiniuser({
          id: this.$route.query.id,
        }).then((response) => {
          this.equipmentInfo = response.data[0];
          this.userarr = response.data;
          // this.setData(this.equipmentInfo,true);
          this.getEquipmentList(this.equipmentInfo.uphone)
        });
      },
      getEquipmentList(phone) {
        getListByPhone({
          phone
        }).then(res => {
          if (res.data.length > 0) {
            this.seleceVal = res.data[0].deviceId
            this.equipmentList = res.data
            this.equipmentInfo.deviceId = this.seleceVal
            this.getList()
          }
        })
      },
      clearFn() {
        this.queryParams.userName = ''
        this.queryParams.userPhone = ''
        this.queryParams.relativesName = ''
        this.queryParams.relativesPhone = ''
        this.queryParams.equipmentName = ''
      },
      prewarnHandleBlur(e) {
        console.log('光标移开')
        console.log(e)
        console.log(this.queryParams.prewarnTempValue)
        if (this.queryParams.prewarnQuery) {
          this.queryParams.userName = ''
          this.queryParams.userPhone = ''
          this.queryParams.relativesName = ''
          this.queryParams.relativesPhone = ''
          this.queryParams.equipmentName = ''
          switch (this.queryParams.prewarnQuery) {
            case 'userName':
              this.queryParams.userName = this.queryParams.prewarnTempValue
              break;
            case 'userPhone':
              this.queryParams.userPhone = this.queryParams.prewarnTempValue
              break;
            case 'relativesName':
              this.queryParams.relativesName = this.queryParams.prewarnTempValue
              break;
            case 'relativesPhone':
              this.queryParams.relativesPhone = this.queryParams.prewarnTempValue
              break;
            case 'equipmentName':
              this.queryParams.equipmentName = this.queryParams.prewarnTempValue
              break;
          }
        }
      },
      selectTrigger(e) {
        this.queryParams.prewarnQuery = e
      },
      changetime(val) {
        // console.log(val)
        this.time = val
        this.queryParams.startDate = this.time[0]
        this.queryParams.endDate = this.time[1]
      },
      selectable(row, index) {
        if (row.prewarnHealthHandleStatus == '0') {
          return true
        }
      },
      // 点击已处理/未处理tab按钮
      handleUntreated(item) {
        this.queryParams.pageNum = 1
        if (item.tabButtonValue == '未处理') {
          this.tabButtonList[0].selectBtn = false
          this.tabButtonList[1].selectBtn = true
          this.queryParams.prewarnHealthHandleStatus = '0'
        } else if (item.tabButtonValue == '已处理') {
          this.tabButtonList[0].selectBtn = true
          this.tabButtonList[1].selectBtn = false
          this.queryParams.prewarnHealthHandleStatus = '1'
        }
        this.getList();
      },
      /** 查询预警类别列表 */
      getList() {
        if (this.$route.query.prewarnHealthDeviceId) {
          this.queryParams.prewarnHealthDeviceId = this.$route.query.prewarnHealthDeviceId
        }
        this.loading = true;
        listPrewarn(this.queryParams).then(response => {
          this.prewarnList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          prewarnId: null,
          prewarnHealthType: null,
          prewarnHealthValue: null,
          prewarnHealthTime: null,
          prewarnHealthContent: null,
          prewarnHealthStatus: "0",
          prewarnHealthDeviceId: null,
          prewarnHealthDeviceUserid: null,
          prewarnHealthDeviceContactid: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.userName = ''
        this.queryParams.userPhone = ''
        this.queryParams.relativesName = ''
        this.queryParams.relativesPhone = ''
        this.queryParams.equipmentName = ''
        this.queryParams.startDate = null
        this.queryParams.endDate = null
        this.time = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.prewarnId)
        if (selection.length !== 0) {
          this.single = false
        } else {
          this.single = true
        }
        // this.single = selection.length!==0
        // this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加预警类别";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const prewarnId = row.prewarnId || this.ids
        getPrewarn(prewarnId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改预警类别";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.prewarnId != null) {
              updatePrewarn(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addPrewarn(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 批量处理按钮操作 */
      handleBtn(row) {
        let prewarnIds = [];
        if (row.prewarnId) {
          prewarnIds.push(row.prewarnId)
        } else {
          prewarnIds = this.ids
        }
        // const prewarnIds = row.prewarnId || this.ids;
        this.$confirm('确认需要处理当前' + prewarnIds.length + '条预警消息吗？', '批量处理', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateHandlePrewarn({
            prewarnId: prewarnIds.join(',')
          }).then(res => {
            if (res.code == 200) {
              this.getList();
              this.$modal.msgSuccess("处理成功");
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
        // this.$modal.confirm(,'提示',{
        //   confirmButtonText: '处理',
        //   cancelButtonText: '取消',
        // }).then(function() {
        //   console.log('昂达个的双方各')
        //   // return delPrewarn(prewarnIds);
        // }).then(() => {
        //
        // }).catch(() => {});
      },
      // 用户详情
      handleDelete(row) {
        this.$router.push({
          path: '/userdet?id=' + row.prewarnHealthDeviceUserid + '&uphone=' + row.userPhone
        })
        // /userdet?id=310&uphone=15175183601
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/health/prewarn/export', {
          ...this.queryParams
        }, `prewarn_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
